package com.cc.util;



import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;


/**
 * Created by cc on 2017/6/7.
 */




public class SqlHelper {
    private static Connection ct = null;
//	private static PreparedStatement ps = null;
//	private static ResultSet rs = null;

    /*
     * DataBase Parameter
     */
    static String url = "";
    static String driver = "";
    static String username = "";
    static String password = "";

    static Properties pp = null;
    static FileInputStream fis = null;
    static String path = "";

    /*
     * static code for loading driver
     */
    static{
        try {
            pp = new Properties();
            path = SqlHelper.class.getClassLoader().getResource("db.properties").getPath();
            fis = new FileInputStream(path);
            pp.load(fis);
            url = pp.getProperty("url");
            driver = pp.getProperty("driver");
            username = pp.getProperty("username");
            password = pp.getProperty("password");
            Class.forName(driver);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * obtain connection
     */
    public static Connection getConnection(){
        try {
            ct = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ct;
    }

    /*
     * close stream
     */
    public static void close(ResultSet rs,PreparedStatement ps, Connection ct){
        if(rs!=null){
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            rs=null;
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            ps=null;
        }
        if(ct!=null){}
        try {
            ct.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ct=null;
    }

}

